package com.example.autopia.model.Repositories

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.example.autopia.model.Item.Car
import com.example.autopia.model.Item.Card
import com.example.autopia.model.Item.Comment
import com.example.autopia.model.Item.News
import com.example.autopia.model.Item.User
import com.example.autopia.utilities.KEY_BD_NEWS
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener

class NewsRepository {
    private val database = FirebaseDatabase.getInstance()
    private var reference = database.getReference(KEY_BD_NEWS)

    fun addNews(news: News): Boolean {
        var status = false
        val newItem = reference.push()
        news.id = newItem.key ?: ""
        newItem.setValue(news)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun deleteNews(newsId: String): Boolean {
        var status = false
        reference.child(newsId).removeValue()
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun addLike(newsId: String): Boolean {
        var status = false
        reference.child(newsId).child("likes").get().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val newsData = task.result.value
                if (newsData != null) {
                    // Проверьте, что данные не пусты, а затем увеличьте значение likes
                    val currentLikes = newsData as Long
                    val updatedLikes = currentLikes + 1
                    reference.child(newsId).child("likes").setValue(updatedLikes)
                    status = true
                }
            } else {
                // Обработайте ошибку, если операция завершилась неудачно
                val exception = task.exception
                if (exception != null) {
                    // Обработайте исключение
                }
            }
        }
        return status
    }

    fun removeLike(newsId: String): Boolean {
        var status = false
        reference.child(newsId).child("likes").get().addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val newsData = task.result.value
                if (newsData != null) {
                    // Проверьте, что данные не пусты, а затем увеличьте значение likes
                    val currentLikes = newsData as Long
                    val updatedLikes = currentLikes - 1
                    reference.child(newsId).child("likes").setValue(updatedLikes)
                    status = true
                }
            } else {
                // Обработайте ошибку, если операция завершилась неудачно
                val exception = task.exception
                if (exception != null) {
                    // Обработайте исключение
                }
            }
        }
        return status
    }

    fun addComment(newsId: String, comment: Comment): Boolean {
        var status = false
        val newItem = reference.child(newsId).child("comments").push()
        comment.id = newItem.key ?: "0"
        newItem.setValue(comment)
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun removeComment(newsId: String, commentId: String): Boolean {
        var status = false
        reference.child(newsId).child("comments").child(commentId).removeValue()
            .addOnCompleteListener {
                status = true
            }.addOnFailureListener { err ->
            }
        return status
    }

    fun getAllItems(): MutableLiveData<ArrayList<News>> {
        val itemsList = ArrayList<News>()
        val result = MutableLiveData<ArrayList<News>>()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                for (itemSnapshot in dataSnapshot.children) {
                    val id = itemSnapshot.child("id").value.toString()
                    val likes = itemSnapshot.child("likes").value.toString().toInt()
                    val logo = itemSnapshot.child("logo").value.toString()
                    val mainText = itemSnapshot.child("mainText").value.toString()
                    val name = itemSnapshot.child("name").value.toString()
                    val title = itemSnapshot.child("title").value.toString()
                    val viewType = itemSnapshot.child("viewType").value.toString().toInt()
                    val photo = itemSnapshot.child("photo").value.toString()
                    val time = itemSnapshot.child("time").value.toString().toInt()
                    val userid = itemSnapshot.child("userid").value.toString()
                    val commentsList = ArrayList<Comment>()
                    var verificated = 0
                    if (itemSnapshot.child("userverificated").value!=null){
                        verificated = itemSnapshot.child("userverificated").value.toString().toInt()
                    }
                    for (comments in itemSnapshot.child("comments").children) {
                        val id = comments.child("id").value.toString()
                        val time = comments.child("time").value.toString().toInt()
                        val text = comments.child("text").value.toString()
                        val username = comments.child("username").value.toString()
                        val userphoto = comments.child("userphoto").value.toString()
                        val userid = comments.child("userid").value.toString()
                        val com = Comment(id, username, userphoto, text, time, userid)
                        commentsList.add(com)
                    }
                    //val comments = itemSnapshot.child("comments").getValue(Comment::class.java)
                    val news = News(
                        id,
                        logo,
                        name,
                        likes,
                        commentsList,
                        title,
                        mainText,
                        viewType,
                        photo,
                        time,
                        userid,
                        verificated
                    )
                    itemsList.add(news)
                    // Log.d("Yatoro", news.toString())
                }
                Log.d("Yatoro", "В списке  новостей " + itemsList.size.toString())
                result.value = itemsList
            }

            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Yatoro", "Ошибка в News")
            }
        })
        return result
    }

    fun getNewsById(id: String): MutableLiveData<News> {
        val news: MutableLiveData<News> = MutableLiveData()
        reference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val currentSnapshot = dataSnapshot.child(id)
                if (currentSnapshot.exists()) {
                    val id = currentSnapshot.child("id").value.toString()
                    val likes = currentSnapshot.child("likes").value.toString().toInt()
                    val logo = currentSnapshot.child("logo").value.toString()
                    val mainText = currentSnapshot.child("mainText").value.toString()
                    val name = currentSnapshot.child("name").value.toString()
                    val title = currentSnapshot.child("title").value.toString()
                    val viewType = currentSnapshot.child("viewType").value.toString().toInt()
                    val photo = currentSnapshot.child("photo").value.toString()
                    val time = currentSnapshot.child("time").value.toString().toInt()
                    val userid = currentSnapshot.child("userid").value.toString()
                    val commentsList = ArrayList<Comment>()
                    var verificated = 0
                    if (currentSnapshot.child("userverificated").value!=null){
                        verificated = currentSnapshot.child("userverificated").value.toString().toInt()
                    }
                    for (comments in currentSnapshot.child("comments").children) {
                        val id = comments.child("id").value.toString()
                        val time = comments.child("time").value.toString().toInt()
                        val text = comments.child("text").value.toString()
                        val username = comments.child("username").value.toString()
                        val userphoto = comments.child("userphoto").value.toString()
                        val userid = comments.child("userid").value.toString()
                        val com = Comment(id, username, userphoto, text, time, userid)
                        commentsList.add(com)
                    }
                    news.value = News(
                        id,
                        logo,
                        name,
                        likes,
                        commentsList,
                        title,
                        mainText,
                        viewType,
                        photo,
                        time,
                        userid,
                        verificated
                    )
                } else {

                }
            }

            override fun onCancelled(databaseError: DatabaseError) {
                // Обработка ошибки
            }
        })
        return news
    }
}